const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取帖子评论
router.get('/posts/:postId/comments', (req, res) => {
  const { postId } = req.params;
  db.query(`
    SELECT c.*, u.username 
    FROM comments c
    JOIN users u ON c.user_id = u.id
    WHERE c.post_id = ?
    ORDER BY c.created_at DESC
  `, [postId], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

// 添加评论
router.post('/posts/:postId/comments', (req, res) => {
  const { postId } = req.params;
  const { content } = req.body;
  const userId = req.user.id; // 从认证中间件获取

  db.query(
    'INSERT INTO comments (post_id, user_id, content) VALUES (?, ?, ?)',
    [postId, userId, content],
    (error, results) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ 
        id: results.insertId, 
        message: '评论发布成功' 
      });
    }
  );
});

module.exports = router; 